const fs = require('fs')
const path = require('path')
const qs = require('querystring')
const http = require('http')
const server = http.createServer()

server.on('request', (req, res) => {
    if (req.url === '/s') {
        fs.readFile(path.join(__dirname, 'data/city.json'), (err, data) => {
            if (err) return console.log(err)
            const arr = JSON.parse(data.toString())
            // console.log(arr)
            // const arr1 = Object.values(arr)
            let arr2 = []
            arr.map(item => arr2.push(item.provinceName))
            res.setHeader('Content-Type', 'application/json;charset=utf-8')
            res.end(JSON.stringify(arr2))
        })
    }
    else if (req.url.startsWith('/qu')) {
        const queryStr = req.url.split('?')[1]
        // 把查询参数字符串 转成 JS 对象结构
        const query = qs.parse(queryStr)
        console.log(query)
        const pname = query.pname
        console.log(pname)
        fs.readFile(path.join(__dirname, 'data/city.json'), (err, data) => {
            if (err) return console.log(err)
            const arr = JSON.parse(data.toString())
            const arr1 = arr.filter((item, index) => item.provinceName === pname)
            console.log(arr1)
            const aa = arr1[0].cities.map(item => item.cityName)
            res.setHeader('Content-Type', 'application/json;charset=utf-8')
            res.end(JSON.stringify(aa))
        })
    } else if (req.url.startsWith('/xian')) {
        const cc = req.url.split('?')[1].split('&')[1]
        const dd = req.url.split('?')[1]
        // console.log(cc)
        const ccc = qs.parse(cc)
        const ddd = qs.parse(dd)
        const pname = ddd.pname
        const cname = ccc.cname
        console.log(dd)
        fs.readFile(path.join(__dirname, 'data/city.json'), (err, data) => {
            if (err) return console.log(err)
            const arr = JSON.parse(data.toString())
            const arr1 = arr.filter(item => item.provinceName === pname)
            const arr2 = arr1[0].cities.filter(item => item.cityName === cname)
            const arr3 = arr2[0].counties.map(item => item.countyName)

            res.setHeader('Content-Type', 'application/json;charset=utf-8')
            res.end(JSON.stringify(arr3))
        })
    }
})

server.listen(4444, () => {
    console.log('服务器启动了！')
})

// fs.readFile(path.join(__dirname, 'data/city.json'), (err, data) => {
//     if (err) return console.log(err)
//     const arr = JSON.parse(data.toString())
//     const arr2 = arr.filter(item => {
//         return item.provinceName === '湖北省'
//     })
//     console.log(arr2[0].cities.map(item => {
//         return item.cityName
//     }))
//     const arr3 = arr2[0].cities.filter(item => {
//         return item.cityName === '武汉市'
//     })
//     console.log(arr3[0].counties.map(item => {
//         return item.countyName
//     }))
// })